<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>客户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="5">
          <el-select
            v-model="typevalue"
            @change="searchSelect(typevalue)"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.rolesName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="8"
          ><el-input
            placeholder="请输入用户名"
            v-model="selectMsg.msg"
            clearable
            @clear="selectUserList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handSelect"
            ></el-button> </el-input></el-col
        ><el-col :span="4">
          <el-button type="primary" @click="addDialogvisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userlist" border style="width: 100%" stripe>
        <el-table-column fixed="left" type="index" label="#"></el-table-column>
        <el-table-column prop="use.id" label="用户id" width="100">
        </el-table-column>
        <el-table-column prop="use.nickName" label="昵称" width="120">
        </el-table-column>
        <el-table-column prop="use.username" label="账号" width="120">
        </el-table-column>
        <el-table-column prop="use.password" label="密码" width="120">
        </el-table-column>
        <el-table-column prop="use.age" label="年龄" width="100">
        </el-table-column>
        <el-table-column prop="use.sex" label="性别" width="120">
        </el-table-column>
        <el-table-column prop="use.phone" label="手机" width="120">
        </el-table-column>
        <el-table-column
          prop="use.mailbox"
          label="邮箱"
          width="120"
        ></el-table-column>
        <el-table-column prop="rolesName" label="角色名称" width="120">
        </el-table-column>
        <el-table-column prop="use.createdTime" label="注册时间">
        </el-table-column>
        <el-table-column prop="use.isActived" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.use.isActived"
              @change="userStatechanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEidtDialog(scope.row.id, scope.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserInfo(scope.$index, scope.row.use.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="Cast(scope.row.use.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.pager.currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="this.pager.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.pager.total"
      >
      </el-pagination>
    </el-card>
    <!-- 编辑用户对话框区域 -->
    <el-dialog
      title="编辑用户信息"
      :visible.sync="editDialogvisible"
      width="70%"
    >
      <!-- 内容主体区域 -->
      <span>
        <!-- 内容主体区域 -->
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="70px"
        >
          <!-- 用户名 -->
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <!-- 昵称 -->
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="editForm.nickname"></el-input>
          </el-form-item>
          <!-- 密码 -->
          <el-form-item label="密码" prop="password">
            <el-input v-model="editForm.password"></el-input>
          </el-form-item>
          <!-- 备注 -->
          <el-form-item label="备注" prop="remark">
            <el-input v-model="editForm.remark"></el-input>
          </el-form-item> </el-form
      ></span>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogvisible = false">取 消</el-button>
        <el-button type="primary" @click="editSave()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户对话框区域 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogvisible"
      width="50%"
      @close="addDialogclosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <!-- 昵称 -->
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="addForm.nickname"></el-input>
        </el-form-item>
        <!-- 账号 -->
        <el-form-item label="账号" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <!-- 年龄 -->
        <el-form-item label="年龄" prop="age">
          <el-input v-model="addForm.age"></el-input>
        </el-form-item>
        <!-- 性别 -->
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="radio" label="1" @change="changeRadio()"
            >男</el-radio
          >
          <el-radio v-model="radio" label="0" @change="changeRadio()"
            >女</el-radio
          >
        </el-form-item>
        <!-- 电话 -->
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="mailbox">
          <el-input v-model="addForm.mailbox"></el-input>
        </el-form-item>
        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogvisible = false">取 消</el-button>
        <el-button type="primary" @click="AddAdmin()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框区域 -->
    <el-dialog title="角色分配" :visible.sync="castVisible" width="30%">
      <span>
        <el-select
          v-model="putRole.roleId"
          @change="searchCast()"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.rolesName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="castVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePutRoles()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  mounted () {
    this.getRoles()
    this.getUserList()
  },
  data () {
    // 自定义验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 正确的邮箱
        return cb()
      }
      cb(new Error('请输入正确的邮箱'))
    }
    // 自定义验证手机号规则
    var checkMobile = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^1[3-9]\d{9}$/
      if (regMobile.test(value)) {
        // 验证通过
        return callback()
      } else {
        // 验证不通过，返回提示信息
        return callback(new Error('请输入正确的手机号'))
      }
    }
    return {
      // 用户id
      userId: '',
      // radio初始数据
      radio: '1',
      // 用户数据
      userlist: [
      ],
      // 搜索框内容
      selectMsg: {
        msg: '',
        currentPage: '',
        pageSize: '',
        total: ''
      },
      // 要操作的行
      currentIndex: 0,
      // 分页用到的数据
      pager: {
        currentPage: 1,
        pageSize: 5
      },
      // 控制添加用户对话框的显示和隐藏，默认为false
      addDialogvisible: false,
      // 添加用户表单数据
      addForm: {
        nickname: '',
        username: '',
        password: '',
        age: '',
        sex: 1,
        phone: '',
        mailbox: '',
        remark: ''
      },
      // 添加用户表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          { min: 1, max: 2, message: '请填写正确的年龄', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      // 控制编辑用户对话框的显示和隐藏，默认为false
      editDialogvisible: false,
      // 控制分配角色对话框的显示和隐藏，默认为false
      castVisible: false,
      // 获取到的用户信息
      editForm: {
        id: '',
        nickname: '',
        username: '',
        password: '',
        remark: ''
      },
      // 修改用户表单验证规则
      editFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      },
      // 角色列表
      options: [],
      typevalue: '',
      putRole: {
        roleId: '',
        userId: ''
      }
    }
  },
  created () {
  },
  methods: {
    // 获取radio选中值
    changeRadio () {
      console.log(this.radio)
    },
    // 添加用户
    async AddAdmin () {
      console.log(this.addForm)
      this.addForm.age = parseInt(this.addForm.age)
      this.addForm.phone = parseInt(this.addForm.phone)
      if (!this.addForm.remark) this.addForm.remark = '无'
      const { data: res } = await this.$http.post('users', this.addForm)
      if (res.code === 1000) {
        if (this.selectMsg.msg) {
          this.SelectUser(this.selectMsg, this.typevalue)
        } else {
          if (this.typevalue) {
            this.getUsersByRoleId(this.typevalue)
          } else {
            this.getUserList(this.pager)
          }
        }
        this.addDialogvisible = false
        alert('注册成功')
      } else {
        alert(`${res.msg}`)
      }
    },
    // 用户名查找用户
    handSelect () {
      this.pager.currentPage = 1
      if (this.selectMsg.msg) {
        this.SelectUser(this.selectMsg, this.typevalue)
      } else {
        if (this.selectMsg.msg) {
          this.SelectUser(this.selectMsg, this.typevalue)
        } else {
          if (this.typevalue) {
            this.getUsersByRoleId(this.typevalue)
          } else {
            this.getUserList(this.pager)
          }
        }
      }
    },
    // 删除用户
    async removeUserInfo (index, id) {
      console.log(index)
      // 弹框询问用户是否确认删除用户
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 取消
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      await this.$http.delete(`users/${id}`)
      this.currentIndex = index
      this.userlist.splice(this.currentIndex, 1)
      this.getUserList()
    },
    // 获取角色列表
    async getRoles () {
      const { data: res } = await this.$http.get('roles')
      this.options = res.data
      console.log(this.options)
    },
    // 确定修改角色按钮
    async savePutRoles () {
      this.putRole.roleId = parseInt(this.putRole.roleId)
      this.putRole.userId = parseInt(this.putRole.userId)
      const { data: res } = await this.$http.put('users/roles/', this.putRole)
      console.log(res)
      this.castVisible = false
      if (this.selectMsg.msg) {
        this.SelectUser(this.selectMsg, this.typevalue)
      } else {
        if (this.typevalue) {
          this.getUsersByRoleId(this.typevalue)
        } else {
          this.getUserList(this.pager)
        }
      }
    },
    // 选择器获取到选中值的id
    searchSelect (id) {
      this.pager.currentPage = 1
      this.getUsersByRoleId(id)
    },
    // 角色选择器获取选中值
    searchCast () {
      console.log(this.putRole.roleId)
    },
    // 根据角色id获取角色列表
    async getUsersByRoleId (id) {
      var params = this.pager
      const { data: res } = await this.$http.get(`users/Roles/${id}`, { params: params })
      this.userlist = res.data
      this.pager.total = res.count
    },
    // 获取用户列表
    async getUserList () {
      console.log(this.pager)
      const { data: res } = await this.$http.get('users', { params: this.pager })
      this.userlist = res.data
      console.log(res.data)
      this.pager.total = res.count
    },
    // 监听 switch 开关状态变化的事件
    async userStatechanged (row) {
      console.log(row)
      const { data: res } = await this.$http.put(`users/statu/${row.use.id}`, row.use)
      if (res.code !== 1000) {
        row.isActived = !row.isActived
        return this.$message.error('更新用户状态失败！')
      }
      return this.$message.success('更新用户状态成功！')
    },
    // 用户名查寻方法
    async SelectUser (params, id) {
      if (!id) id = 0
      console.log(params.msg)
      params.currentPage = this.pager.currentPage
      params.pageSize = this.pager.pageSize
      params.total = this.pager.total
      const { data: res } = await this.$http.get(`users/select/${id}`, { params: params })
      console.log(res)
      if (res.data) {
        this.userlist = res.data
        this.pager.total = res.count
      } else {
        this.userlist = []
      }
    },
    // 监听添加用户对话框关闭的事件
    addDialogclosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 分配角色
    Cast (id) {
      this.castVisible = true
      console.log(id)
      this.putRole.userId = id
    },
    // 展示用户编辑的对话框
    async showEidtDialog (index, row) {
      this.currentIndex = index
      this.editDialogvisible = true
      console.log(row)
      this.editForm.id = row.use.id
      this.editForm.nickname = row.use.nickName
      this.editForm.username = row.use.username
      this.editForm.password = row.use.password
      this.editForm.remark = row.use.remarks
    },
    // 保存编辑用户
    async editSave () {
      this.editDialogvisible = false
      this.EidtUser(this.editForm, this.editForm.id)
    },
    // 编辑用户方法
    async EidtUser (data, id) {
      console.log(data)
      const { data: res } = await this.$http.put(`users/${id}`, data)
      console.log(res)
      this.getUserList()
    },
    // 监听修改用户对话框关闭事件
    editDialogclosed () {
      this.$refs.editFormRef.resetFields()
    },
    handleSizeChange (newSize) {
      // pagesize改变触发
      this.pager.pageSize = newSize
      if (this.selectMsg.msg) {
        this.SelectUser(this.selectMsg, this.typevalue)
      } else {
        if (this.typevalue) {
          this.getUsersByRoleId(this.typevalue)
        } else {
          this.getUserList(this.pager)
        }
      }
    },
    handleCurrentChange (newPage) {
      // 页码改变触发
      this.pager.currentPage = newPage
      if (this.selectMsg.msg) {
        this.SelectUser(this.selectMsg, this.typevalue)
      } else {
        if (this.typevalue) {
          this.getUsersByRoleId(this.typevalue)
        } else {
          this.getUserList(this.pager)
        }
      }
    },
    // 清空搜索框重新获取数据
    selectUserList () {
      if (this.typevalue) {
        this.getUsersByRoleId(this.typevalue)
      } else {
        this.getUserList(this.pager)
      }
    }
  }
}
</script>

<style scoped>
</style>
